import { ActionReducerMapBuilder, createAsyncThunk, createSlice, PayloadAction } from "@reduxjs/toolkit";
import { UserInfo } from "@/type/UserInfoType";
import { fetchUserInfoAPI } from "@/api/userInfoAPI";


type InitialState = {
   userInfo: UserInfo
}
const initialState: InitialState = {
   userInfo: {} as UserInfo,
};

/**
 * @description 获取用户信息的AsyncThunk函数
 * */
export const fetchUserInfoThunk = createAsyncThunk("fetchUserInfoThunk", async (_, { rejectWithValue }) => {
   try {
      const { data: { userInfo } } = await fetchUserInfoAPI();
      return userInfo;
   } catch (error: any) {
      return rejectWithValue(error.message);
   }
});

const userInfoStore = createSlice({
   name: "userInfoStore",
   initialState,
   reducers: {},
   extraReducers(builder: ActionReducerMapBuilder<InitialState>) {
      builder.addCase(fetchUserInfoThunk.fulfilled, (state: InitialState, action: PayloadAction<UserInfo>) => {
         state.userInfo = action.payload;
      });
   },
});

export default userInfoStore.reducer
